<template>
  <div class="app-container calendar-list-container">
    <div v-if="!importedByPreview" class="filter-container" style="margin-bottom:20px">
      <span style="margin-right:10px">上课日期</span>
      <el-date-picker
        v-model="dateformat"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        style="width: 240px">
      </el-date-picker>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;margin-left: 10px" class="filter-item" placeholder="课程标签、主题" v-model="listQuery.tagOrTopic">
      </el-input>
      <el-select v-model="listQuery.lessonType" style="width:120px;margin-left:10px" placeholder="课程类型">
        <el-option
          v-for="item in options"
          :key="item.code"
          :label="item.msg"
          :value="item.code">
        </el-option>
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button v-if='!importedByCreate' class="filter-item" style="margin-left: 10px;" @click="$router.push('./add')" :type="pageBoolean.addColor" icon="el-icon-plus">{{ pageBoolean.addText }}</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="handleAllDelete" :type="pageBoolean.delColor" icon="el-icon-delete">{{ pageBoolean.delText }}</el-button> -->
      <el-button v-if='importedByCreate' type="success" @click='saveLessonForCreate'>保存</el-button>
    </div>

    <el-table
      ref='list'
      @select='getEveryPageSlectionChanged'
      @select-all='getEveryPageSlectionAllChanged'
      :key='tableKey'
      :data="list"
      v-loading="listLoading"
      element-loading-text="数据加载中，请稍后" 
      border 
      fit 
      highlight-current-row 
      select-on-indeterminate
      style="width: 100%">
      <el-table-column  v-if='importedByCreate' type="selection" width="40">
      </el-table-column>
      
      <el-table-column align="center" label="ID" min-width="60">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上课主题" min-width="120">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.lessonTopic}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="课程标签" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.tag}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100" align="center" label="课程类型" prop="isFreeDesc"></el-table-column>
      <el-table-column min-width="100" align="center" label="上课日期" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.scheduleTime|dateformat('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="上课时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.teachingStartTime|dateformat('HH:mm')}} - {{scope.row.teachingEndTime|dateformat('HH:mm') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="授课老师" min-width="120">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.teacherName}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="类型" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.lessonTypeDesc}}</span>
        </template>
      </el-table-column>

      <el-table-column v-if='!importedByCreate && !importedByPreview' align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="lessonModify(scope.row)">编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="warnBefrorDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog v-if='!importedByCreate && !importedByPreview &&dialogFormVisible'  top="4%" width="70%" title="编辑页" :visible.sync="dialogFormVisible" class="dialogModifyLessonManage">
      <curriculum-add :modify-data='modifyData' @modifycomplete="modifyComplete"></curriculum-add>
    </el-dialog>
  </div>
</template>

<script>
/**
 * 1、声明一个数组 lessonData ，用于存储默认选中的课程
 * 2、打开 课程列表后， 遍历 lessonData, 使用 ele ui 的方法，将数组中存在的 选项选中，如果在此过程中 触发了 selectChange,想办法声明一个锚，阻止 selecttions 与 lessonData 作对比
 * 3、切换 分页页面时，做法同 步骤2
 * 4、当 用户 主动触发 selectChange 事件时，将 lessonData 与 selections 作对比，增删 lessonData中的数据，对比依据为课程 id
 * 5、关闭 课程列表后，将lessonData,而不是 selections 传递出来
*/
import { getLessonsList, getLessonDetail, deleteLesson, getLessonEnums } from '@/api/curriculum'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import curriculumAdd from '@/views/curriculum/add'
export default {
  name: 'list',
  props:{
    isCreateCommodity:{
      type:Boolean,
      default:false
    },
    defaultSelectedLessons:{
      type:Array,
      default:() => []
    },
    isPreviewLessons:{
      type:Boolean,
      default:false
    },
    defaultPreviewLessons:{
      type:Array,
      default:() => []
    },
    defaultLessonType:{
      default:1
    }
  },
  components: { curriculumAdd },
  data() {
    return {
      options:[],
      importedByCreate:this.isCreateCommodity,
      selectedLessons:this.defaultSelectedLessons,
      importedByPreview:this.isPreviewLessons,
      previewLessons:this.defaultPreviewLessons,
      previewLessonType:this.defaultLessonType,
      headers:{},
      inputVisible:false,
      inputValue:'',
      modifyData:'',
      brandListOptions: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      dateformat:'',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        lessonType: '',
        tagOrTopic:'',
        pageNo: 1,
        pageSize: 10,
        startDate: '',
        endDate: ''
      },
      temp: {
        labels:[]
      },
      dialogFormVisible: false,
      tableKey: 0,
      pageBoolean:{
        delColor:'primary',
        delText:'批量删除',
        addColor:'success',
        addText:'添加课程'
      },
      selectedLessonsCount:0,
      currentPageInitalSelectedLessons:[]
    }
  },
  created() {
    if(this.importedByPreview){
      this.listLoading = false
      this.list = this.previewLessons
      this.total = this.previewLessons.length
    }
    getLessonEnums().then(res => {
      const { data } = res
      this.options = data
      if(this.importedByCreate){
        this.listQuery['lessonType'] = this.previewLessonType
      }
    })
  },
  mounted() {
    // this.getSections()
    if(this.importedByCreate){
      const params = this.dealDataForGetList()
      params['lessonType'] = this.previewLessonType
      getLessonsList(params).then(response => {
        const { code, data:{ total, data, list } = { total:0, data:[] } } = response
        if(code == 0){
          this.total = total
          this.list = data || list
          this.listLoading = false
          this.$nextTick(() => {
            this.initalSelectedLessonsInChangeGoods()
          })
        }
      }).catch(reject => {
        this.listLoading = false
      })
    }else{
      if(!this.importedByPreview){
        this.headers = { accessToken:getToken() }
        this.getList()
      }
    }
  },
  watch:{
    showAllDel(val){
      if(val){
        this.pageBoolean.delText = '选择删除'
        this.pageBoolean.delColor = 'danger'
      }else{
        this.pageBoolean.delText = '批量删除'
        this.pageBoolean.delColor = 'primary'
      }
    },
    multipleSelection(val){
      if(val.length == 0){
        this.pageBoolean.delText = '选择删除'
        this.pageBoolean.delColor = 'danger'
      }else{
        this.pageBoolean.delText = '确定删除'
        this.pageBoolean.delColor = 'success'
      }
    }
  },
  methods: {
    dealDataForGetList() {
      this.listLoading = true
      const params = this.listQuery
      const { dateformat } = this
      if(dateformat){
        params.startDate = dateformat[0]
        params.endDate = dateformat[1]
      }else{
        delete params.startDate
        delete params.endDate
      }
      return params
    },
    getList() {
      const params = this.dealDataForGetList()
      if(this.importedByPreview){
        this.listLoading = false
        this.list = this.previewLessons.slice((params.pageNo - 1) * params.pageSize, params.pageNo * params.pageSize)
        this.total = this.previewLessons.length
        return false
      }
      getLessonsList(params).then(response => {
        const { code, data:{ total, data, list } = { total:0, data:[] } } = response
        if(code == 0){
          this.total = total
          this.list = data || list
          this.listLoading = false
          this.$nextTick(() => {
            this.initalSelectedLessonsInChangeGoods()
          })

          // if(total==0){
          //   this.$message({
          //     message:'未找到符合条件的课程！',
          //     type:'warning'
          //   })
          // }
        }
      }).catch(reject => {
        this.listLoading = false
        // this.$message({
        //       message:'未找到符合条件的课程！',
        //       type:'warning'
        //     })
      })
    },
    lessonModify(row) {
      getLessonDetail(row.id).then(response => {
        const { code, data } = response
        this.modifyData = data
        // if(row.labelNames){
        //   row.labels = row.labelNames.split(',')
        // }else{
        //   row.labels = []
        // }
        // data.labels = row.labels
        // data.file = [{name:data.cover,url:data.cover}]
        // this.temp = data
        this.dialogFormVisible = true
      })
    },
    modifyComplete(data){
      if(!data) return false
      this.getList()
      this.dialogFormVisible = false
    },
    warnBefrorDelete(idx, row) {
      this.$confirm(
        '确认删除当前课程？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
      ).then(response => { this.lessonDelete(idx, row) })
    },
    lessonDelete(idx, row) {
      deleteLesson(row.id).then(response => {
        const { code } = response
        if(code == 0){
          this.$notify({
            title: '成功',
            message: '删除课程成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(idx)
          this.list.splice(idx, 1)
          this.total--
        }else{
          this.$notify({
            title: '失败',
            message: '删除课程失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    },
    saveLessonForCreate() {
      const { selectedLessons, listQuery:{ lessonType } } = this
      //计算一下两者不和混搭
      let num = 0
      selectedLessons.map(select => {
        if (select['lessonType'] != lessonType){
          num += 1
        }
      })
      if (num > 0) {
        this.$message({
          message: '暂不支持图文视频混合，请先重置已选课程',
          type: 'warning'
        })
        return
      }
      this.$emit('addlessontocommodity', selectedLessons, lessonType)
    },
    operateLessonForCreate() {
      this.$confirm('是否保存当前选择的课程？', {
        confirmButtonText:'保存',
        cancelButtonText:'不保存'
      })
        .then(() => { this.saveLessonForCreate() })
        .catch(() => { })
    },
    initalSelectedLessonsInChangeGoods() {
      if(this.importedByCreate){
        this.selectedLessonsCount = 0
        this.currentPageInitalSelectedLessons = []
        this.selectedLessons.forEach(row => {
          this.list.forEach((list, index) => {
            if(list.id == row.id){
              this.$refs.list.toggleRowSelection(this.list[index], true)
              this.currentPageInitalSelectedLessons.push(this.list[index])
              this.selectedLessonsCount++
              return
            }
          })
        })
      }
    },
    dealCurrentPageSelected(targetNode, selection, row) {
      const replaceMent = [...this[targetNode]]
      if(this.selectedLessonsCount > selection.length){
        replaceMent.forEach((lesson, index) => {
          if(lesson.id == row.id){
            replaceMent.splice(index, 1)
            return
          }
        })
      } else{
        replaceMent.push(row)
      }
      this[targetNode] = replaceMent
    },
    getEveryPageSlectionChanged(selection, row){
      if(this.importedByCreate){
        this.dealCurrentPageSelected('selectedLessons', selection, row)
        this.dealCurrentPageSelected('currentPageInitalSelectedLessons', selection, row)
        this.selectedLessonsCount = selection.length
      }
    },
    dealCurrentPageAllSelected(targetNode, selection){
      const replaceMent = [...this[targetNode]]
      const parentSelect = (selection.length == 0) ? this.currentPageInitalSelectedLessons : selection
      parentSelect.forEach((row) => {
        replaceMent.forEach((lesson, index) => {
          if(lesson.id == row.id){
            replaceMent.splice(index, 1)
          }
        })
      })
      selection.forEach((row, index) => {
        replaceMent.push(row)
      })
      this[targetNode] = replaceMent
    },
    getEveryPageSlectionAllChanged(selection){
      if(this.importedByCreate){
        this.dealCurrentPageAllSelected('selectedLessons', selection)
        this.dealCurrentPageAllSelected('currentPageInitalSelectedLessons', selection)
        this.selectedLessonsCount = selection.length
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

.app-container{
  padding:20px;
}
.pagination-container{
  margin-top:30px;
}
</style>
<style rel="stylesheet/scss" lang="scss">
.dialogModifyLessonManage{
  .el-dialog__header{
    padding-bottom: 0;
  }
  .el-dialog__body{
    padding:0
  }
  .createPost-main-container{
    padding: 20px 0 !important;
  }
}
</style>